package cn.wolfcode.p2p.website.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.service.IAccountService;
import cn.wolfcode.p2p.base.service.IRealAuthService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.base.util.BidConst;
import cn.wolfcode.p2p.base.util.LoginInfoContext;
import cn.wolfcode.p2p.business.domain.BidRequest;
import cn.wolfcode.p2p.business.query.BidRequestQuery;
import cn.wolfcode.p2p.business.service.IBidRequestService;

/**
 * 首页控制器
 * 
 * @author Administrator
 *
 */
@Controller
public class IndexController {
	@Autowired
	private IBidRequestService bidRequestService;
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private IAccountService accountService;
	@Autowired
	private IRealAuthService realAuthService;

	/**
	 * 访问首页
	 */
	@RequestMapping("/")
	public String main(Model model) {
		model.addAttribute("unPublishBidRequest", bidRequestService.listUnPlushBideRequest(5));
		model.addAttribute("bidRequests", bidRequestService.listIndexBidRequest(5));
		return "main";
	}

	/**
	 * 投资列表
	 */
	@RequestMapping("/invest")
	public String invest() {

		return "invest";
	}

	/**
	 * 投资列表
	 */
	@RequestMapping("/invest_list")
	public String invest_list(Model model, @ModelAttribute("qo") BidRequestQuery qo) {
		qo.setStates(new int[] { BidConst.BIDREQUEST_STATE_BIDDING, BidConst.BIDREQUEST_STATE_PAYING_BACK,
				BidConst.BIDREQUEST_STATE_COMPLETE_PAY_BACK });
		model.addAttribute("pageInfo", bidRequestService.query(qo));
		return "invest_list";
	}

	/**
	 * 前台借款详情
	 */
	@RequestMapping("/borrow_info")
	public String borrowInfo(Model model, Long id) {
		// 借款信息
		BidRequest br = bidRequestService.get(id);
		model.addAttribute("bidRequest", br);
		// 借款人信息
		UserInfo borrowUser = userInfoService.get(br.getCreateUser().getId());
		model.addAttribute("userInfo", borrowUser);

		// 实名认证信息
		model.addAttribute("realAuth", realAuthService.get(br.getCreateUser().getId()));

		// 当前用户的
		LoginInfo current = LoginInfoContext.getCurrentLoginInfo();
		if (current != null){
			if (current.getId().equals(borrowUser.getId())){
				model.addAttribute("self", true);
			}else {
				model.addAttribute("self", false);
				model.addAttribute("account", accountService.get(current.getId()));
			}
		}
		return "borrow_info";
	}

}
